/**
 * 二分查找
 * author: zhuoyifan
 * 2020-11-29
 */

function binarySearch(arr, val) {
  let low = 0;
  let high = arr.length - 1;
  let mid = 0;
  while (low <= high) {
    mid = Math.floor((low + high) / 2);
    if (val === arr[mid].id) {
      return mid;
    } else if (val > arr[mid].id) {
      low = mid + 1;
    } else {
      high = mid - 1;
    }
  }
  return -1;
}

/*
let arr = [
  {id: 1, title: 'constructor属性', description: '...', content: '.....', date: new Date()},
  {id: 2, title: '即将被删除', description: '...', content: '.....', date: new Date()},
  {id: 3, title: 'constructor属性', description: '...', content: '.....', date: new Date()},
  {id: 4, title: 'constructor属性', description: '...', content: '.....', date: new Date()},
  {id: 5, title: 'constructor属性', description: '...', content: '.....', date: new Date()},
];
let index = binarySearch(arr, 3);
console.log(index);

arr.splice(index, 1);
console.log(arr);
*/

export default binarySearch;
